package com.dog.basics.admin.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.cron.CronUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dog.basics.bean.model.mtkj.*;
import com.dog.basics.service.mtkj.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;


@Slf4j
@Component
@AllArgsConstructor
public class OrderTask {
    private final IMtOrderService mtOrderService;
    private final IMtGoodsService mtGoodsService;
    private final IMtOrderGoodsService mtOrderGoodsService;
    private final IMtCouponService mtCouponService;
    private final IMtGoodsSkuService mtGoodsSkuService;
    private final IMtShoppingService mtShoppingService;
    private final IMtShoppingAccountService mtShoppingAccountService;
    private final IMtFlowingWaterService mtFlowingWaterService;

    //定时
    @Bean
    public void cancelOrder() {
        CronUtil.setMatchSecond(true);
        CronUtil.start(false);
        CronUtil.getScheduler().clear();
        //每三十分钟执行一次
        CronUtil.schedule("0 0/20 * * * ?", new Runnable() {
            @Override
            @Transactional(rollbackFor = Exception.class)
            public void run() {
                //判断如果订单三十分钟未支付取消订单
                Long minutes = DateUtil.offsetMinute(DateUtil.date(), -30).getTime() / 1000L;
                // 获取30分钟之前未支付的订单
                List<MtOrder> orderList = mtOrderService.list(Wrappers.<MtOrder>lambdaQuery().le(MtOrder::getCreateTime, minutes).eq(MtOrder::getRefundStatus, 0));
                if (CollUtil.isNotEmpty(orderList)) {
                    for (int i = 0; i < orderList.size(); i++) {
                        MtOrder mtOrder = orderList.get(i);
                        mtOrder.setRefundStatus(5);
                        mtOrder.setUpdateBy(-1L);
                        mtOrder.setUpdateTime(DateUtil.currentSeconds());
                        List<MtOrderGoods> list = mtOrderGoodsService.list(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, mtOrder.getId()));
                        list.forEach(e -> {
                            //判断商品是否存在
                            MtGoods mtGoods = mtGoodsService.getById(e.getGoodsId());
                            //   Validator.validateNotNull(mtGoods, "商品不存在!");
                            //判断SKU是否存在
                            MtGoodsSku mtGoodsSku = mtGoodsSkuService.getById(e.getSkuId());
                            if (ObjectUtil.isNotNull(mtGoodsSku)) {
                                //Validator.validateNotNull(mtGoodsSku, "商品sku不存在!");
                                //增加库存
                                mtGoodsSku.setStock(mtGoodsSku.getStock() + e.getNum());
                                Validator.validateTrue(mtGoodsSkuService.updateById(mtGoodsSku), "库存增加失败!");
                            }

                        });
                        //返回优惠券
                        if (ObjectUtil.isNotNull(mtOrder.getCouponId()) && !Validator.equal(mtOrder.getCouponId(), -1L)) {
                            MtCoupon mtCoupon = mtCouponService.getById(mtOrder.getCouponId());

                            if (ObjectUtil.isNotNull(mtCoupon)) {
                                //  Validator.validateNotNull(mtCoupon, "优惠券不存在!");
                                mtCoupon.setStatus(1);
                                //   mtCoupon.setUpdateBy(SecurityUtils.getUser().getUserId());
                                mtCoupon.setUpdateTime(DateUtil.currentSeconds());
                                Validator.validateTrue(mtCouponService.updateById(mtCoupon), "优惠券修改失败!");
                            }

                        }
                        Validator.validateTrue(mtOrderService.updateById(mtOrder), "取消订单失败!");
                    }

                }
            }

        });
        //每天凌晨1点执行
        CronUtil.schedule("0 0 1 * * ?", new Runnable() {
            @Override
            @Transactional(rollbackFor = Exception.class)
            public void run() {
                Long days = DateUtil.offsetDay(DateUtil.date(), -15).getTime() / 1000L;
                // 获取15天之前未支付的订单
                List<MtOrder> orderList = mtOrderService.list(Wrappers.<MtOrder>lambdaQuery().le(MtOrder::getCreateTime, days).eq(MtOrder::getRefundStatus, 7));
                if (CollUtil.isNotEmpty(orderList)) {
                    for (int i = 0; i < orderList.size(); i++) {
                        MtOrder order = orderList.get(i);
                        order.setRefundStatus(8);
                        order.setShippingStatus(3);
                        order.setFinishTime(DateUtil.currentSeconds());
                        //修改订单子项
                        List<MtOrderGoods> list = mtOrderGoodsService.list(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, order.getId()));
                        list.forEach(e -> {
                                    e.setShippingStatus(3);
                                    Validator.validateTrue(mtOrderGoodsService.updateById(e), "确认收货失败!");
                                    //商品销售数量增加
                                    MtGoods mtGoods = mtGoodsService.getById(e.getGoodsId());
                                    if (ObjectUtil.isNotNull(mtGoods)) {
                                        mtGoods.setSales(mtGoods.getSales() + e.getNum());
                                        Validator.validateTrue(mtGoodsService.updateById(mtGoods), "修改商品失败!");
                                    }
                                    MtShopping mtShopping = mtShoppingService.getById(e.getShopId());
                                    if (ObjectUtil.isNotNull(mtShopping)) {
                                        mtShopping.setSales(mtShopping.getSales() + e.getNum());
                                        Validator.validateTrue(mtShoppingService.updateById(mtShopping), "修改店铺失败!");
                                    }
                                }
                        );
                        Validator.validateTrue(mtOrderService.updateById(order), "确认收货失败!");
                        //查询店铺账号
                        List<MtShoppingAccount> list1 = mtShoppingAccountService.list(Wrappers.<MtShoppingAccount>lambdaQuery().eq(MtShoppingAccount::getShopId, order.getShopId()).orderByDesc(MtShoppingAccount::getCreateTime));
                        //    Validator.validateTrue(CollUtil.isNotEmpty(list1), "店铺信息不完善");
                        if (CollUtil.isNotEmpty(list1)) {
                            MtShopping mtShopping = mtShoppingService.getById(order.getShopId());
                            BigDecimal shopMoney = BigDecimal.ZERO;
                            if (ObjectUtil.isNotNull(mtShopping)) {
                                shopMoney = order.getPayMoney().multiply(mtShopping.getBl()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            } else {
                                shopMoney = order.getPayMoney();
                            }

                            //开始流水
                            MtShoppingAccount mtShoppingAccount = list1.get(0);
                            mtShoppingAccount.setMoney(mtShoppingAccount.getMoney().add(shopMoney));
                            mtShoppingAccount.setUpdateTime(DateUtil.currentSeconds());
                            Validator.validateTrue(mtShoppingAccountService.updateById(mtShoppingAccount), "店铺增加余额失败!");
                            //支付记录流水(用户)
                            MtFlowingWater mtFlowingWater = new MtFlowingWater();
                            mtFlowingWater.setSerialNo(order.getOrderNo());
                            mtFlowingWater.setWaterUserId(order.getUserId());
                            mtFlowingWater.setWaterShopId(order.getShopId());
                            mtFlowingWater.setWaterMoney(order.getPayMoney().negate());
                            mtFlowingWater.setWaterType(0);
                            mtFlowingWater.setWaterAccount(0);
                            mtFlowingWater.setInoutType(0);
                            mtFlowingWater.setWaterExplain("用户订单支付");
                            mtFlowingWater.setCreateTime(DateUtil.currentSeconds());
                            mtFlowingWater.setCreateBy(order.getUserId());
                            Validator.validateTrue(mtFlowingWaterService.save(mtFlowingWater), "用户流水增加失败!");
                            MtFlowingWater mtFlowingWater1 = new MtFlowingWater();
                            mtFlowingWater1.setSerialNo(order.getOrderNo());
                            mtFlowingWater1.setWaterUserId(order.getUserId());
                            mtFlowingWater1.setWaterShopId(order.getShopId());
                            mtFlowingWater1.setWaterMoney(shopMoney);
                            mtFlowingWater1.setWaterType(1);
                            mtFlowingWater1.setWaterAccount(0);
                            mtFlowingWater1.setInoutType(3);
                            mtFlowingWater1.setWaterExplain("订单结算");
                            mtFlowingWater1.setCreateTime(DateUtil.currentSeconds());
                            mtFlowingWater1.setCreateBy(order.getUserId());
                            Validator.validateTrue(mtFlowingWaterService.save(mtFlowingWater1), "用户流水增加失败!");
                        }

                    }

                }
            }

        });
        //夜里23:00执行
        CronUtil.schedule("0 0 23 * * ?", new Runnable() {
            @Override
            @Transactional(rollbackFor = Exception.class)
            public void run() {
                //获取过期的优惠券 进行更新
                List<MtCoupon> list = mtCouponService.list(Wrappers.<MtCoupon>lambdaQuery().le(MtCoupon::getEndTime, DateUtil.currentSeconds()).eq(MtCoupon::getStatus, 1));
                if (CollUtil.isNotEmpty(list)) {
                    //更新为过期
                    list.forEach(e -> e.setStatus(3));
                    //更新状态
                    mtCouponService.updateBatchById(list);
                }


            }

        });

    }

}
